<template>
  <div class="page-content">
    <dovecote-info v-if="!showEcharts"></dovecote-info>
    <el-row v-if="!showEcharts" type="flex" class="dovecote_data" :gutter="2">
      <el-col :span="6">
        <el-card class="mini_card">
          近7日入孵：<i
            style="font-size: 16px; font-weight: 900; color: #ffd700"
            >{{ sevenData.one }}</i
          >
          个
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="mini_card">
          近7日光蛋：<i
            style="font-size: 16px; font-weight: 900; color: #03a9f4"
            >{{ sevenData.two }}</i
          >
          个
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="mini_card">
          近7日出仔：<i
            style="font-size: 16px; font-weight: 900; color: #9acd32"
            >{{ sevenData.three }}</i
          >
          个
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="mini_card">
          近7日回头蛋：<i
            style="font-size: 16px; font-weight: 900; color: #ff4040"
            >{{ sevenData.four }}</i
          >个
        </el-card>
      </el-col>
    </el-row>
    <TableBar :showTop="false" :columns="columns" @changeColumn="changeColumn" @changeEcharts="changeEcharts">
      <div slot="bottom">
        <div>
          <el-button type="primary" plain @click="showAddDialog"
            >新增记录</el-button
          >
          <el-button type="danger" plain @click="deleteBox">批量删除</el-button>
          <!-- <el-button type="success" plain @click="showDialog('add')">导入</el-button> -->
          <el-button type="success" plain @click="exportExcel">导出</el-button>
          <el-date-picker
            v-model="dateValue"
            type="date"
            @change="pickDate"
            value-format="yyyy-M-d"
            placeholder="选择日期"
            style="margin-left: 15px"
          >
          </el-date-picker>
        </div>
      </div>
    </TableBar>
    <the-table
      :data="data"
      :showPage="false"
      ref="table"
      :default-sort="{ prop: 'laborTime', order: 'descending' }"
      @getDataBySelectBox="selectChange"
      v-if="!showEcharts"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        label="饲养员姓名"
        prop="breeder"
        v-if="columns[0].show"
        sortable
      />
      <el-table-column
        label="入孵数量"
        prop="one"
        v-if="columns[1].show"
        sortable
      />
      <el-table-column
        label="光蛋数量"
        prop="two"
        v-if="columns[2].show"
        sortable
      />
      <el-table-column
        label="出仔数量"
        prop="three"
        v-if="columns[3].show"
        sortable
      />
      <el-table-column
        label="回头蛋数量"
        prop="four"
        v-if="columns[4].show"
        sortable
      />
      <el-table-column
        label="日期"
        prop="laborTime"
        v-if="columns[5].show"
        sortable
      >
        <template slot-scope="scope">
          {{ scope.row.laborTime.slice(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column label="时段" prop="timeFrame" v-if="columns[6].show">
        <template slot-scope="scope">
          <el-tag effect="dark" v-if="scope.row.timeFrame == '上午'"
            >上午</el-tag
          >
          <el-tag
            effect="dark"
            type="danger"
            v-if="scope.row.timeFrame == '下午'"
            >下午</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        prop="gmtModified"
        v-if="columns[7].show"
        sortable
      />
      <el-table-column fixed="right" label="操作" width="150px">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="editRecord(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            style="color: #fa6962"
            icon="el-icon-delete"
            @click="removeById(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </the-table>
    <div v-if="showEcharts">
      <el-row :gutter="20">
        <el-col :span="12"><el-card><ChartsOne :data="chartsData.one" :title="'近7天入孵数量'" :xTitle="chartsData.oneTitle"/></el-card></el-col>
        <el-col :span="12"><el-card><ChartsTwo :data="chartsData.two" :title="'近7天光蛋数量'" :xTitle="chartsData.twoTitle"/></el-card></el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 20px">
        <el-col :span="12"><el-card><ChartsThree :data="chartsData.three" :title="'近7天出仔数量'" :xTitle="chartsData.threeTitle"/></el-card></el-col>
        <el-col :span="12"><el-card><ChartsFour :data="chartsData.four" :title="'近7天回头蛋数量'" :xTitle="chartsData.fourTitle"/></el-card></el-col>
      </el-row>
    </div>
    <div class="pagination" v-if="!showEcharts">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"

        :current-page="queryInfo.pageNum"
        :page-sizes="[8, 16, 32, 64]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="form" label-width="100px" :rules="rules">
        <el-form-item label="鸽棚编号" prop="dovecoteNumber">
          <el-select v-model="form.dovecoteNumber" placeholder="请选择鸽棚编号">
            <el-option
              v-for="item in options"
              :key="item.dovecoteId"
              :label="item.dovecoteNumber"
              :value="item.dovecoteNumber"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入孵量">
          <el-input-number v-model="form.one" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="光蛋量">
          <el-input-number v-model="form.two" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="出仔量">
          <el-input-number v-model="form.three" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="回头蛋量">
          <el-input-number v-model="form.four" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="日期" prop="laborTime">
          <el-date-picker
            v-model="form.laborTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="时段" prop="timeFrame">
          <el-select v-model="form.timeFrame" placeholder="请选择时段">
            <el-option
              v-for="item in dateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import TableBar from "@/components/Dovecote/TableBar";
import ChartsOne from "@/components/Dovecote/ChartsOne";
import ChartsTwo from "@/components/Dovecote/ChartsTwo";
import ChartsThree from "@/components/Dovecote/ChartsThree";
import ChartsFour from "@/components/Dovecote/ChartsFour";
import {
  getData,
  addRecord,
  editRecord,
  deleteRecord,
  getByDate,
  exportExcel,
  getSevenDay,
  getSevenDayDetail
} from "@/api/Dovecote/InfoManage/IncubationRecord.js";
import { mapState } from "vuex";
import { getAllCage } from "@/api/common.js";
export default {
  name: "IncubationRecord",
  meta: {
    title: "人工孵化记录",
  },
  components: {
    TableBar,
    ChartsOne,
    ChartsTwo,
    ChartsThree,
    ChartsFour
  },
  computed: {
    ...mapState({
      dovecoteNumber: (state) =>
        state.Usersetting.CurrentDovecote.dovecoteNumber,
    }),
  },
  watch: {
    dovecoteNumber(val) {
      this.queryInfo.dovecoteNumber = val;
      this.queryInfo.pageSize = 8;
      this.queryInfo.pageNum = 1;
      this.getData();
    },
  },
  data() {
    return {
      // 对话框
      dialogVisible: false,
      editFlag: false,
      title: "添加记录",
      // 请求用的表单数据
      queryInfo: {
        baseId: JSON.parse(window.sessionStorage.getItem("BaseInfo")).id,
        dovecoteNumber: "",
        pageSize: 8,
        pageNum: 1,
      },
      choosedArray: [], // 选择要被删除的数据数组
      // 要渲染的数据
      data: [],
      value: "",
      options: [],
      dateOptions: [
        { label: "上午", value: "上午" },
        { label: "下午", value: "下午" },
      ],
      total: 0,
      dateValue: "",
      sevenData: {},
      columns: [
        { name: "饲养员姓名", show: true },
        { name: "入孵数量", show: true },
        { name: "光蛋数量", show: true },
        { name: "出仔数量", show: true },
        { name: "回头蛋数量", show: true },
        { name: "日期", show: true },
        { name: "时段", show: true },
        { name: "更新时间", show: true },
      ],
      // 填写表单和规则
      form: {
        baseId: JSON.parse(window.sessionStorage.getItem("BaseInfo")).id,
        one: 0,
        two: 0,
        three: 0,
        four: 0,
        timeFrame: "",
        laborTime: "",
      },
      rules: {
        dovecoteNumber: [
          { required: true, message: "请选择鸽棚编号", trigger: "blur" },
        ],
        timeFrame: [{ required: true, message: "请选择时段", trigger: "blur" }],
        laborTime: [{ required: true, message: "请选择日期", trigger: "blur" }],
      },
      // 是否展示Echarts
      showEcharts: false,
      chartsData: {
        one: [],
        two: [],
        three: [],
        four: [],
        oneTitle: [],
        twoTitle: [],
        threeTitle: [],
        fourTitle: []
      },
    };
  },
  created() {
    this.init();
  },
  methods: {
    async init() {
      await getAllCage({ baseId: this.queryInfo.baseId }).then((res) => {
        // console.log(res)
        if (res.data.statusCode === 20000) {
          this.options = res.data.data;
          if (this.options.length > 0) {
            this.queryInfo.dovecoteNumber = this.options[0].dovecoteNumber;
            this.getData();
            this.countSevenData();
          }
        } else {
          return this.$message.error("获取鸽棚选项错误");
        }
      });
      await getSevenDayDetail(this.queryInfo).then(res => {
        console.log(res)
        if(res.data.statusCode === 20000) {
          for(let item of res.data.data) {
            item.laborTime = item.laborTime.slice(0, 10);
            this.chartsData.one.push(item.one);
            this.chartsData.two.push(item.two);
            this.chartsData.three.push(item.three);
            this.chartsData.four.push(item.four);
            this.chartsData.oneTitle.push(item.laborTime);
            this.chartsData.twoTitle.push(item.laborTime);
            this.chartsData.threeTitle.push(item.laborTime);
            this.chartsData.fourTitle.push(item.laborTime);
          }
        }
      })
    },
    async getData() {
      await getData(this.queryInfo).then((res) => {
        // console.log(res);
        if (res.data.statusCode === 20000) {
          this.data = res.data.data.records;
          this.total = res.data.data.total;
        } else {
          return this.$message.error("获取孵化记录错误");
        }
      });
    },
    async countSevenData() {
      await getSevenDay(this.queryInfo).then((res) => {
        if (res.data.statusCode === 20000) {
          this.sevenData = res.data.data;
          // console.log(this.sevenData);
        } else {
          return this.$message.error("获取最近七天数量错误");
        }
      });
    },
    async getByDovecoteNumber(e) {
      this.queryInfo.dovecoteNumber = e;
      this.queryInfo.pageSize = 8;
      this.queryInfo.pageNum = 1;
      if (e === "") {
        this.queryInfo.dovecoteNumber = this.options[0].dovecoteNumber;
      }
      this.getData();
    },
    // 展示Echarts
    changeEcharts(e) {
      this.showEcharts = e;
    },
    // 对话框初始化
    showAddDialog() {
      // console.log(this.dovecoteNumber);
      this.title = "添加记录";
      this.editFlag = false;
      this.dialogVisible = true;
      this.form = {
        baseId: JSON.parse(window.sessionStorage.getItem("BaseInfo")).id,
        one: 0,
        two: 0,
        three: 0,
        four: 0,
        timeFrame: "",
        laborTime: "",
      };
    },
    editRecord(row) {
      this.form = row;
      this.editFlag = true;
      this.title = "修改记录";
      this.dialogVisible = true;
    },
    // 选择日期
    pickDate(e) {
      if (!e) {
        this.getData();
      } else {
        const arr = e.split("-");
        this.queryInfo.year = arr[0];
        this.queryInfo.month = arr[1];
        this.queryInfo.day = arr[2];
      }
      this.queryInfo.pageSize = 10;
      this.queryInfo.pageNum = 1;
      this.getByDate();
    },
    async getByDate() {
      await getByDate(this.queryInfo).then((res) => {
        // console.log(res);
        if (res.data.statusCode === 20000) {
          this.data = res.data.data.records;
          this.total = res.data.data.total;
        } else {
          return this.$message.error("获取孵化记录错误");
        }
      });
    },
    submit() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return false;
        if (this.editFlag) {
          this.edit();
        } else {
          this.add();
        }
      });
    },
    async add() {
      await addRecord(this.form).then((res) => {
        // console.log(res);
        if (res.data.statusCode === 20000) {
          this.$message.success("添加记录成功！");
          this.dialogVisible = false;
          this.getData();
          this.countSevenData();
        } else {
          return this.$message.error(res.data.message);
        }
      });
    },
    async edit() {
      const id = this.form.id;
      delete this.form.id;
      delete this.form.breeder;
      delete this.form.gmtCreate;
      delete this.form.gmtModified;
      await editRecord(id, this.form).then((res) => {
        if (res.data.statusCode === 20000) {
          this.$message.success("修改记录成功！");
          this.dialogVisible = false;
          this.getData();
          this.countSevenData();
        } else {
          return this.$message.error(res.data.message);
        }
      });
    },
    async removeById(id) {
      const confirmResult = await this.$confirm(
        "此操作将删除该记录, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult === "confirm") {
        await deleteRecord(id).then((res) => {
          if (res.data.statusCode === 20000) {
            this.$message.success("删除成功！");
            this.getData();
            this.countSevenData();
          } else {
            this.$message.error(res.data.message);
          }
        });
      }
    },
    // 多选删除
    async deleteBox() {
      const confirmResult = await this.$confirm(
        "此操作将删除所选记录, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult === "confirm") {
        this.choosedArray.forEach(async (e) => {
          await deleteRecord(e.id).then((res) => {
            if (res.data.statusCode === 20000) {
              this.getData();
              this.countSevenData();
            } else {
              return this.$message.error(res.data.message);
            }
          });
          this.$message.success("删除成功！");
        });
      }
    },
    // 页码改变和列表可视化改变
    handleSizeChange(val) {
      this.queryInfo.pageSize = val;
      if (this.chooseForm.type == "0") {
        this.getData();
      } else {
        this.getByType();
      }
    },
    handleCurrentChange(val) {
      this.queryInfo.pageNum = val;
      if (this.chooseForm.type == "0") {
        this.getData();
      } else {
        this.getByType();
      }
    },
    changeColumn(columns) {
      this.columns = columns;
      this.$refs.table.doLayout();
    },
    selectChange(selection) {
      this.choosedArray = selection;
    },
    async exportExcel() {
      await exportExcel(this.queryInfo.baseId).then((res) => {
        if (res.status === 200) {
          // console.log(res);
          const blob = new Blob([res.data], {
            // res 为后台返回数据
            type: "application/vnd.ms-excel;charset=utf-8", // 导出数据生成excel的格式设置
          });
          if ("download" in document.createElement("a")) {
            // 非IE下载
            const elink = document.createElement("a");
            elink.download = `人工孵化记录.xlsx`;
            elink.style.display = "none";
            elink.target = "_blank";
            elink.href = window.URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.search {
  background-color: #fafafa;
  width: 100%;
  height: auto;
  border-radius: 10px;
  padding: 10px;
  margin-bottom: 10px;
  .search_input {
    display: inline-block;
    width: 300px;
    .el-button {
      background-color: #409eff;
      color: #fafafa;
    }
  }
}
.search_card {
  height: 100%;
}
.pagination {
  margin-top: 20px;
  text-align: center;
}
.dovecote_data {
  margin: 10px 0;
  .mini_card {
    display: flex;
    justify-content: center;
    // flex-direction: column;
    align-items: center;
    width: 95%;
    height: 70px;
    font-size: 15px;
    letter-spacing: 2px;
  }
}
.operaBar {
  margin: 20px 0;
  display: flex;
  justify-content: space-between;
}
</style>